package com.employment.service.impl;

import com.employment.dao.UserMapper;
import com.employment.entity.User;
import com.employment.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 用户服务实现类
 * 
 * @author Employment System
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createUser(User user) {
        try {
            return userMapper.insert(user) > 0;
        } catch (Exception e) {
            log.error("创建用户失败: ", e);
            throw new RuntimeException("创建用户失败");
        }
    }

    @Override
    public User getUserById(Long userId) {
        return userMapper.selectOneById(userId);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userMapper.selectByUsername(username) != null;
    }

    @Override
    public boolean existsByEmail(String email) {
        return userMapper.selectByEmail(email) != null;
    }

    @Override
    public boolean existsByPhone(String phone) {
        return userMapper.selectByPhone(phone) != null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateLastLoginInfo(Long userId, String ip) {
        try {
            return userMapper.updateLastLoginInfo(userId, ip) > 0;
        } catch (Exception e) {
            log.error("更新登录信息失败: ", e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        try {
            User user = userMapper.selectOneById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }

            // 验证原密码
            if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
                return false;
            }

            // 更新新密码
            user.setPassword(passwordEncoder.encode(newPassword));
            return userMapper.update(user) > 0;
        } catch (Exception e) {
            log.error("修改密码失败: ", e);
            throw new RuntimeException("修改密码失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean resetPassword(String email, String verificationCode, String newPassword) {
        try {
            // 验证验证码
            String cacheKey = "verification_code:" + email;
            String cachedCode = (String) redisTemplate.opsForValue().get(cacheKey);
            
            if (cachedCode == null || !cachedCode.equals(verificationCode)) {
                return false;
            }

            // 查询用户
            User user = userMapper.selectByEmail(email);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }

            // 更新密码
            user.setPassword(passwordEncoder.encode(newPassword));
            boolean success = userMapper.update(user) > 0;

            // 删除验证码
            if (success) {
                redisTemplate.delete(cacheKey);
            }

            return success;
        } catch (Exception e) {
            log.error("重置密码失败: ", e);
            throw new RuntimeException("重置密码失败");
        }
    }

    @Override
    public boolean sendVerificationCode(String email) {
        try {
            // 检查邮箱是否存在
            User user = userMapper.selectByEmail(email);
            if (user == null) {
                throw new RuntimeException("邮箱未注册");
            }

            // 生成6位验证码
            String verificationCode = String.format("%06d", new Random().nextInt(999999));

            // 存储到Redis，有效期5分钟
            String cacheKey = "verification_code:" + email;
            redisTemplate.opsForValue().set(cacheKey, verificationCode, 5, TimeUnit.MINUTES);

            // TODO: 发送邮件
            log.info("发送验证码到邮箱: {}, 验证码: {}", email, verificationCode);

            return true;
        } catch (Exception e) {
            log.error("发送验证码失败: ", e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(User user) {
        try {
            return userMapper.update(user) > 0;
        } catch (Exception e) {
            log.error("更新用户信息失败: ", e);
            throw new RuntimeException("更新用户信息失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean disableUser(Long userId) {
        try {
            User user = userMapper.selectOneById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }

            user.setStatus(0); // 0-禁用
            return userMapper.update(user) > 0;
        } catch (Exception e) {
            log.error("禁用用户失败: ", e);
            throw new RuntimeException("禁用用户失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean enableUser(Long userId) {
        try {
            User user = userMapper.selectOneById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }

            user.setStatus(1); // 1-启用
            return userMapper.update(user) > 0;
        } catch (Exception e) {
            log.error("启用用户失败: ", e);
            throw new RuntimeException("启用用户失败");
        }
    }
}